class Book < ActiveRecord::Base
 
  acts_as_taggable
 
  
  has_one :user
  has_one :condition

   #validation
  validates_length_of :title, :within => 3..100
  validates_presence_of :isbn
  validates_presence_of :condition_id
  validates_presence_of :user_id
  validates_presence_of :tag_list
  #comment
  
  #class Methods
  def self.getAllBooks
    find(:all, :order => "title")
  end
  
  #An easy way to see all of the books taht I own.
  def self.getMyBooks(userId)
    find(:all, :conditions => {:user_id => userId, :wanted => 0})
    #, :wanted => "IS NULL"
    #:conditions => {:user_id => params[:id]}
  end
  
  #A method to return the books that I want
  def self.getMyWantedBooks(userId)
        find(:all, :conditions => {:user_id => userId, :wanted => 1})
  end
  
  #this should go to the database and find all the books that others own that have
  #similar titles and ISBN's to the books the current user wants. 
  #this is probably going to be one of the more difficult finds we do in this app.
  #Conditions are:
    #user_id = logged in user AND wanted = 1 (true)
    # AND user_id != logged in AND wanted = 0 (false)
    # AND isbn's are a match, or titles are close. 
  def self.find_matched_with_my_owned(user_id)
    Book.find(:all, :conditions => [ " user_id != ? AND wanted = 0 AND title in ( select title from books where user_id = ? and wanted = 1) ", user_id, user_id] )
  end
  

  
  #a way to search for books based on the first letter of the books title
  def self.find_by_first_letter(letter) 
    find(:all, :conditions => ['ucase(left(title,1)) = ?',letter ], :order => 'title')
  end
  
  def self.search(search)
    if !search.to_s.empty?
      tokens = search.split.collect {|c| "%#{c.downcase}%" }
      find_by_sql(["select b.* from books b where #{ (["(lower(b.title) like ? or lower(b.isbn) like ?)"] * tokens.size).join(" and ") } order by b.title", *(tokens * 2).sort])
    else
      []
    end
  end
  
end
